package com.wdb.modules.security.service;

import com.wdb.exception.BadRequestException;
import com.wdb.modules.security.service.dto.JwtUserDto;
import com.wdb.modules.system.domain.User;
import com.wdb.modules.system.service.DataService;
import com.wdb.modules.system.service.RoleService;
import com.wdb.modules.system.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * UserDetailsService 的实现
 *
 * @author: wendaobai@qq.com
 * @date: 2024/1/16 0016 10:05
 */
@Slf4j
@RequiredArgsConstructor
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
  private final UserCacheManager userCacheManager;
  private final UserService userService;
  private final RoleService roleService;
  private final DataService dataService;

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    JwtUserDto jwtUserDto = userCacheManager.getUserCache(username);
    if (jwtUserDto == null) {
      // 从数据库获取
      User user;
      try {
        user = userService.getLoginData(username);
      } catch (Exception e) {
        // SpringSecurity会自动转换UsernameNotFoundException为BadCredentialsException
        throw new UsernameNotFoundException(username, e);
      }
      if (user == null) {
        throw new UsernameNotFoundException("用户名为空");
      } else {
        if (!user.getEnabled()) {
          throw new BadRequestException("账号未激活！");
        }
        jwtUserDto =
            new JwtUserDto(
                user, dataService.getDeptIds(user), roleService.mapToGrantedAuthorities(user));
      }
    }

    log.info("jwtUserDto:{}", jwtUserDto);
    return jwtUserDto;
  }
}
